#include "parser.h"
#include "stdlib.h"
#include "stdio.h"
#include "yacc.tab.h"
#include "symtable.h"
#include "structtable.h"
#include <string.h>

void print_node(FILE *fd, struct ast_node *n);
void print_identifier(FILE *fd, struct ast_node *node, int include_type, int exclude_last_child);

// file descriptor for global data
FILE *fd_global;

/* returns the string interpretation of a token
 */
char *parse_vartype(int token) {
	switch (token) {
		case DD_KEYWORD_INT: return "int";
		case DD_KEYWORD_FLOAT: return "float";
		case DD_KEYWORD_STRUCT: return "struct";
		case DD_KEYWORD_VOID: return "void";
		default: return "void";
	}
}

/* print arguments for a function
 * node: group containing arguments
 * include_type: if arguments should include its type
 * start_with_comma: if it should include comma before first argument
 * 	(in case there are other arguments before this)
 */
void print_arguments(FILE *fd, struct ast_node *node, int start_with_comma) {
	for (int i = 0; i < node->children.elements; i++) {
		if (start_with_comma || i != 0) fprintf(fd, ", ");
		struct ast_node *element = dd_da_get(&node->children, i);
		print_identifier(fd, element, 1, 0);
	}
}

void print_argument_expressions(FILE *fd, struct ast_node *node, int start_with_comma) {
	for (int i = 0; i < node->children.elements; i++) {
		if (start_with_comma || i != 0) fprintf(fd, ", ");
		struct ast_node *element = dd_da_get(&node->children, i);
		print_node(fd, element);
	}
}

void print_identifier(FILE *fd, struct ast_node *node, int include_type, int exclude_last_child) {
	struct entry *e = symtable_entryat(node->value);
	if (!e) {
		fprintf(stderr, "parser_c: print_identifier: could not find symtable entry at %d\n", node->value);
		exit(-1);
	}

	// if type is needed, print it
	if (include_type) {
		fprintf(fd, "%s ", parse_vartype(e->token));
		if (e->token == DD_KEYWORD_STRUCT) fprintf(fd, " %s *", struct_entryat(e->value)->name);
	}

	// internal variable - width
	if (e->token == DD_INTERNAL_WIDTH) {
		fprintf(fd, "DD_GAME_WIDTH", e->lexptr);
	}
	else
	// internal variable - height
	if (e->token == DD_INTERNAL_HEIGHT) {
		fprintf(fd, "DD_GAME_HEIGHT", e->lexptr);
	}
	// normal variable
	else {
		if (exclude_last_child && node->children.elements == 0) return;
		else fprintf(fd, "%s", e->lexptr);
	}

	for (int i = 0; i < node->children.elements; i++) {

		// some variables print less of the children
		if (exclude_last_child && i+1 >= node->children.elements) break;
		struct ast_node *child = dd_da_get(&node->children, i);
		struct entry *e = symtable_entryat(child->value);
		if (!e) {
			fprintf(stderr, "parser_c: print_identifier children: could not find symtable entry at %d\n", child->value);
			exit(-1);
		}
		fprintf(fd, "->%s", e->lexptr);
	}
}

void print_node(FILE *fd, struct ast_node *n) {

	// parse node
	struct entry *e;
	struct ast_node *child;
	struct struct_entry *se;
	int i;
	switch (n->node_type) {

		/* the game itself, parent of all nodes
		 * contains statements, just print them all one by one
		 */
		case AST_GROUP:
		case AST_GROUP_STATEMENTS:
		case AST_GAME: 
			for (int i = 0; i < n->children.elements; i++) {
				print_node(fd, (struct ast_node *) dd_da_get(&n->children, i));
				if (n->node_type == AST_GROUP_STATEMENTS) fprintf(fd, ";\n");
			}
			break;

		/* identifier, just print it
		 */
		case AST_IDENTIFIER: print_identifier(fd, n, 0, 0); break;

		/* number
		 */
		case AST_NUMBER: fprintf(fd, "%d", n->value); break;

		/* string
		 * get value from symbol table
		 */
		case AST_STRING: {
			struct entry *e = symtable_entryat(n->value);
			if (!e) {
				fprintf(stderr, "parser_c: string: could not find symtable entry at %d\n", n->value);
				exit(-1);
			}
			fprintf(fd, "%s", e->lexptr);
			break;
		}

		/* definition
		 * <type> child1;
		 */
		case AST_DEFINITION: {
			struct ast_node *child = dd_da_get(&n->children, 0);
			print_identifier(fd, child, 1, 0);
			fprintf(fd, ";\n");
			break;
		}

		/* function definition
		 */
		case AST_FUNCTION_DEFINITION: {
			e = symtable_entryat(n->value);
			if (!e) {
				fprintf(stderr, "parser_c: function_definition: could not find symtable entry at %d\n", n->value);
				exit(-1);
			}
			print_identifier(fd, n, 1, 0);
			fprintf(fd, "(");

			// arguments
			struct ast_node *group = dd_da_get(&n->children, 0);
			print_arguments(fd, group, 0);

			fprintf(fd, ") {\n", parse_vartype(e->token), e->lexptr);
			print_node(fd, (struct ast_node *) dd_da_get(&n->children, 1));
			fprintf(fd, "}\n");
			break;
		}

		/* function definition
		 */
		case AST_FUNCTION_CALL: {
			struct ast_node *variable = dd_da_get(&n->children, 0);
			print_identifier(fd, variable, 0, 0);
			fprintf(fd, "(");

			/* called when a function from a struct is called
			 * the struct is the first argument
			 */
			if (variable->children.elements != 0) {
				print_identifier(fd, variable, 0, 1);
			}

			/* other arguments
			 */
			struct ast_node *group = dd_da_get(&n->children, 1);
			print_argument_expressions(fd, group, variable->children.elements != 0);
			fprintf(fd, ")");
			break;
		}

		/* equality
		 * child1 = child2;
		 */
		case AST_ASSIGNMENT: {
			struct ast_node *identifier = dd_da_get(&n->children, 0);
			print_identifier(fd, identifier, 0, 0);
			fprintf(fd, " = ");
			print_node(fd, (struct ast_node *) dd_da_get(&n->children, 1));
			fprintf(fd, "");
			break;
		}

		case AST_OPERATOR_BINARY:
			fprintf(fd, "(");
			print_node(fd, (struct ast_node *) dd_da_get(&n->children, 0));

			char *type;
			switch (n->value) {
				case '<': type = "<"; break;
				case '>': type = ">"; break;
				case '+': type = "+"; break;
				case '-': type = "-"; break;
				case '*': type = "*"; break;
				case '/': type = "/"; break;
				case '=': type = "="; break;
				case DD_OPERATOR_EQ: type = "=="; break;
				case DD_OPERATOR_LE: type = "<="; break;
				case DD_OPERATOR_GE: type = ">="; break;
			}
			fprintf(fd, " %s ", type);

			print_node(fd, (struct ast_node *) dd_da_get(&n->children, 1));
			fprintf(fd, ")");
			break;

		case AST_GROUP_EXPRESSIONS:
			fprintf(fd, "(");
			print_node(fd, (struct ast_node *) dd_da_get(&n->children, 0));
			fprintf(fd, ")");
			break;

		case AST_STRUCT:
			se = struct_entryat(n->value);
			if (!e) {
				fprintf(stderr, "parser_c: struct: could not find symtable entry at %d\n", n->value);
				exit(-1);
			}

			// init struct's appearence
			fprintf(fd, "struct %s {\n", se->name);
			if (se->parent >= 0) {
				fprintf(fd, "	struct %s parent;\n", struct_entryat(se->parent)->name);
			}

			// parse struct's children
			struct ast_node *group = dd_da_get(&n->children, 0);
			for (int i = 0; i < group->children.elements; i++) {
				struct ast_node *child = dd_da_get(&group->children, i);

				// parse functions as signatures
				if (child->node_type == AST_FUNCTION_DEFINITION) {
					e = symtable_entryat(child->value);
					if (!e) {
						fprintf(stderr, "parser_c: struct function definition: "
							"could not find symtable entry at %d\n", n->value);
						exit(-1);
					}

					// is not override function
					if (e->value == 0) {
						fprintf(fd, "%s (*%s)(struct %s*", parse_vartype(e->token), e->lexptr, se->name);
						struct ast_node *group = dd_da_get(&child->children, 0);
						print_arguments(fd, group, 1);
						fprintf(fd, ");\n");
					}
				}
				// parse everything else as normal
				else {
					print_node(fd, child);
				}
			}
			fprintf(fd, "};\n");

			// forward declaration of create function, so it can be referenced
			fprintf(fd, "struct %s *%s_create();\n", se->name, se->name);

			// struct's functions
			for (int i = 0; i < group->children.elements; i++) {
				struct ast_node *child = dd_da_get(&group->children, i);
				if (child->node_type == AST_FUNCTION_DEFINITION) {
					e = symtable_entryat(child->value);
					if (!e) {
						fprintf(stderr, "parser_c: struct functions: "
							"could not find symtable entry at %d\n", child->value);
						exit(-1);
					}
					if (strcmp(e->lexptr, "init") == 0) continue;
					fprintf(fd, "void %s_%s(struct %s *this", se->name, e->lexptr, se->name);
					struct ast_node *group = dd_da_get(&child->children, 0);
					print_arguments(fd, group, 1);
					fprintf(fd, ") {\n");
					print_node(fd, (struct ast_node *) dd_da_get(&child->children, 1));
					fprintf(fd, "}\n");
				}
			}

			// struct's initialiser
			fprintf(fd, "void %s_init(struct %s *this) {\n", se->name, se->name);

			// there is parent, so initialise that
			if (se->parent >= 0) {
				fprintf(fd, "	%s_init(&this->parent);\n", struct_entryat(se->parent)->name);
			}

			// init all structs

			// init based on ast children?
			for (int i = 0; i < group->children.elements; i++) {
				struct ast_node *child = dd_da_get(&group->children, i);

				if (child->node_type == AST_FUNCTION_DEFINITION) {
					e = symtable_entryat(child->value);
					if (!e) {
						fprintf(stderr, "parser_c: struct children: "
							"could not find symtable entry at %d\n", child->value);
						exit(-1);
					}

					// override
					if (e->value != 0) {
						fprintf(fd, "	this->parent.%s = %s_%s;\n", e->lexptr, se->name, e->lexptr);
					}
					else
					// not `init`
					if (strcmp(e->lexptr, "init") != 0) {
						fprintf(fd, "	this->%s = %s_%s;\n", e->lexptr, se->name, e->lexptr);
					}
					// `init` function has special rules
					else {
						struct ast_node *func_child = dd_da_get(&child->children, 1);
						print_node(fd, func_child);
					}
				} else
				if (child->node_type == AST_DEFINITION) {
					struct ast_node *child2 = dd_da_get(&child->children, 0);
					e = symtable_entryat(child2->value);
					if (!e) {
						fprintf(stderr, "parser_c: struct children definition: "
							"could not find symtable entry at %d\n", child2->value);
						exit(-1);
					}
					struct struct_entry *target_struct = struct_entryat(e->value);
					if (e->token == DD_KEYWORD_STRUCT) {
						fprintf(fd, "	this->%s = %s_create();\n", e->lexptr, target_struct->name);
					}

				}
			}

			// close structs init
			fprintf(fd, "}\n");

			// struct's constructor
			fprintf(fd, "struct %s *%s_create() {\n", se->name, se->name);
			fprintf(fd, "	struct %s *temp = malloc(sizeof(struct %s));\n", se->name, se->name);
			fprintf(fd, "	%s_init(temp);\n", se->name, se->name);
			fprintf(fd, "	return temp;\n");
			fprintf(fd, "}\n");
			break;

		/* if statement */
		case AST_IF:
			fprintf(fd, "if (");
			print_node(fd, dd_da_get(&n->children, 0));
			fprintf(fd, ") {\n");
			print_node(fd, dd_da_get(&n->children, 1));
			fprintf(fd, "}\n");
			break;
	} // switch

}

// responsible for creating a file and translating ast to target language
void parse(const char *filename, struct ast_node *n) {
	fd_global = fopen(filename, "w");
	fprintf(fd_global, "#include <stdlib.h>\n");
	fprintf(fd_global, "#include \"world.h\"\n");
	fprintf(fd_global, "#include \"sprite.h\"\n");
	fprintf(fd_global, "#include \"vector2d.h\"\n");
	fprintf(fd_global, "#include \"dd_curves.h\"\n");
	fprintf(fd_global, "#include \"dd_math.h\"\n");
	fprintf(fd_global, "#include \"dd_engine_interface.h\"\n");
	print_node(fd_global, n);
	fclose(fd_global);
}
